package org.raymond.iworks.study.redis.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class RateLimiterTest {
    public static void main(String[] args) throws Exception {
        test();
    }
    public static void test() throws Exception {
        RedissonClient c1 = client();
        RedissonClient c2 = client();
        RRateLimiter rl1 = c1.getRateLimiter("myRateLimiter1");
        RRateLimiter rl2 = c2.getRateLimiter("myRateLimiter2");

        rl1.setRate(RateType.OVERALL, 1, 1, RateIntervalUnit.SECONDS);
        rl2.setRate(RateType.OVERALL, 1, 2, RateIntervalUnit.SECONDS);

        for(int i=0; i<5; i++){
            final int j = i;
            new Thread(()->{
                log.info("1-尝试获取资源: {}", j);
                rl1.acquire();
                log.info("1-得到资源:{}, 当前有效permit:{}", j, rl1.availablePermits());
            }).start();
        }

        for(int i=0; i<5; i++){
            final int j = i;
            new Thread(()->{
                log.info("2-尝试获取资源: {}", j);
                rl2.acquire();
                log.info("2-得到资源:{}, 当前有效permit:{}", j, rl2.availablePermits());
            }).start();
        }

        Thread.sleep(20_000);

        log.info("shutdown");
        c1.shutdown();
        c2.shutdown();
    }

    public static RedissonClient client(){
        Config cfg = new Config();
        cfg.useSingleServer()
                .setAddress("redis://192.168.0.125:6379")
                .setUsername("default")
                .setPassword("123456");
        RedissonClient client = Redisson.create(cfg);
        return client;
    }
}
